package com.baizhi.service.impl;

import com.baizhi.dao.UserDao;
import com.baizhi.User;
import com.baizhi.service.UserService;
import com.baizhi.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

public class UserServiceImpl implements UserService {
    @Override
    public boolean login(String emai, String pwd) {
        List<User> user = new ArrayList<>();
        SqlSession session = MyBatisUtils.openSession();
        try {
            UserDao mapper = session.getMapper(UserDao.class);
            user = mapper.findUser();
            for (User user1 : user) {
                if(user1.getState()==1) {
                    if (emai.equals(user1.getEmail()) && pwd.equals(user1.getPassword())) {
                        return true;
                    }
                }
            }
            return false;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.close(session);
        }
    }

    @Override
    public boolean register(User u, String pwd1) {
        SqlSession session = MyBatisUtils.openSession();
        try {
            UserDao mapper = session.getMapper(UserDao.class);
            if (pwd1.equals(u.getPassword())){
                mapper.register(u);
                session.commit();
                return  true;
            }
        } catch (Exception e) {
            session.rollback();
           throw new RuntimeException(e);
        } finally {
            session.close();
        }
        return false;
    }

    @Override
    public void updateState(String email, int state) {
        SqlSession session = MyBatisUtils.openSession();
        try {
            UserDao userDao = session.getMapper(UserDao.class);
            userDao.updateState(email,state);
            session.commit();
        } catch (Exception e) {
            session.rollback();
            throw new RuntimeException(e);
        } finally {
            session.close();
        }
    }

    @Override
    public User userMessage(String email) {
        SqlSession session = MyBatisUtils.openSession();
        User user=new User();
        try {
            UserDao mapper = session.getMapper(UserDao.class);
            user = mapper.userMessage(email);
            if (user==null){
                user=new User();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
        return user;
    }

    @Override
    public int selectId(String email) {
        SqlSession session = MyBatisUtils.openSession();
        int id = 0;
        try {
            UserDao userDao = session.getMapper(UserDao.class);
            id = userDao.selectId(email);
        } catch (Exception e) {
            throw  new RuntimeException();
        } finally {
            session.close();
        }
        return id;
    }
}
